package com.sharecode.stock.service;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sharecode.stock.exception.StockException;
import com.sharecode.stock.repository.UserRepository;
import com.sharecode.stock.utils.EncryptUtils;
import com.sharecode.stock.vo.User;

@Service
public class UserService {
	@Autowired
	UserRepository userRepository;

	public User login(String username, String password) {
		User user = userRepository.findByUsername(username);
		if (user == null) {
			throw new StockException("用户名或密码错误");
		} else if (user.getErrorCount() > 5) {
			throw new StockException("密码错误超过5次，请联系管理员");
		} else if (StringUtils.equals(user.getPassword(), EncryptUtils.md5Base64(user.getId() + password))) {
			user.setErrorCount(0);
			update(user);
			return user;
		} else {
			user.setErrorCount(user.getErrorCount() + 1);
			update(user);
			throw new StockException("用户名或密码错误");
		}
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void update(User user) {
		userRepository.saveAndFlush(user);
	}

	public static void main(String[] args) {
		String uuid = UUID.randomUUID().toString();
		System.out.println(uuid);
		String passwor = "guest666";
		String md5Base64 = EncryptUtils.md5Base64(uuid + passwor);
		System.out.println(md5Base64);
	}
}
